/**
 * Copyright 2018 asiainfo Inc.
 **/
package com.myz.app.shiro.session;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import java.io.Serializable;

/**
 * DefaultWebSessionManager用于Web环境的实现，可以替代ServletContainerSessionManager自己维护着会话，容器无关。
 * 重新定义SessionManager
 *
 * @author maoyz on 2018/6/11
 * @version: v1.0
 */
public class CustomSessionManager extends DefaultWebSessionManager {

  protected final Logger logger = LoggerFactory.getLogger(CachingShiroSessionDao.class);

  /**
   * retrieve 取回
   * doGetSession()  -->   retrieveSession()
   */
  @Override
  protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
    logger.debug("=================== retrieveSession() =====================");
    // 根据会话秘钥获取session_id
    Serializable sessionId = getSessionId(sessionKey);
    ServletRequest request = null;
    if (sessionKey instanceof WebSessionKey) {
      // 获取request
      request = ((WebSessionKey) sessionKey).getServletRequest();
    }

    if (request != null && sessionId != null) {
      // request中获取session
      Session session = (Session) request.getAttribute(sessionId.toString());
      if (session != null){
        return session;
      }
    }

    Session session =  super.retrieveSession(sessionKey);
    if (request != null && sessionId != null){
      // 将session保证在request中
      request.setAttribute(sessionId.toString(), session);
    }
    return session;
  }
}
